﻿using BackendLogic.BaseLogic;
using ComTools.File;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using ToolsModel;

namespace BackstageWeb.App_Start.Helper
{
    public class BaseController : Controller
    {

        /// <summary>
        /// 请求数据
        /// </summary>
        public string requestInfo { get; set; }


        /// <summary>
        /// 执行action之前的初始化
        /// </summary>
        /// <param name="requestContext">请求上下文</param>
        protected override void Initialize(RequestContext requestContext)
        {
            base.Initialize(requestContext);
            if (requestContext.HttpContext.Request.IsAjaxRequest() && requestContext.HttpContext.Request.RequestType == "POST")
            {
                try
                {
                    this.requestInfo = HttpUtility.UrlDecode(HttpContext.Request.Form.ToString());
                }
                catch (Exception ex)
                {
                    MethodBase methodName = new StackTrace().GetFrame(1).GetMethod();
                    LogHelper.WriteLog("\r\n错误位置:\r\n所属类：" + this.GetType().Name + "\r\n方法名：" + methodName + "\r\n" + ex.ToString());
                    throw ex;
                }
            }
        }

        /// <summary>
        /// 接口专用转换（解压）数据
        /// </summary>
        /// <typeparam name="T">返回类型</typeparam>
        /// <param name="json">json数据</param>
        /// <returns>处理结果</returns>
        public static T DeserializeRequestData<T>(object json)
        {
            return JsonConvert.DeserializeObject<T>(json.ToString());
        }


        /// <summary>
        /// 处理action前
        /// </summary>
        /// <param name="filterContext"></param>
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var loginUser =/*载入后台的用户session信息*/ UserSession.GetLoginUser();

            if (loginUser == null || loginUser.LoginName == null)
            {
                var crtl/*获取请求的控制器路由字符串*/ = filterContext.HttpContext.Request.RequestContext.RouteData.Values["controller"].ToString();

                //排除掉登录和获取验证码的控制器
                if (crtl != "LoginCheck" && crtl != "Login" && crtl != "GetValidateCode")
                {
                    string url = new UrlHelper(filterContext.RequestContext).Action("Index", "Login");
                    //防止ajax调用分部视图出现登陆超时，在局部跳转URL的问题   
                    filterContext.HttpContext.Response.ContentType = "text/html";
                    //$.messager.alert('登录超时','抱歉，您已登录超时，系统将于3秒后返回登录页重新登录','info')
                    filterContext.HttpContext.Response.Write("<script> alert('抱歉，您已登录超时，系统将于3秒后返回登录页重新登录');setTimeout(function(){ window.location.href='" + url + "';},3000); </script>");
                    filterContext.HttpContext.Response.End();
                }
            }
        }

        /// <summary>
        /// 输出到客户端
        /// </summary>
        /// <returns></returns>
        protected ContentResult ReturnResult(object data, string errDetails = null)
        {
            if (!string.IsNullOrEmpty(errDetails))
            {
                if (!errDetails.Contains("ApplicationException"))
                {
                    MethodBase methodName = new StackTrace().GetFrame(1).GetMethod();
                    LogHelper.WriteLog("\r\n错误位置:\r\n所属类：" + this.GetType().Name + "\r\n方法名：" + methodName + "\r\n" + errDetails);
                }
            }
            string resultStr = JsonConvert.SerializeObject(data, new IsoDateTimeConverter() { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" });
            return Content(resultStr);
        }

    }
}